from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from sqlalchemy import text

HOSTNAME = "127.0.0.1"
USERNAME = "root"
PASSWORD = "root"
PORT = 3306
DATABASE = "flask_database"

app = Flask(__name__)

app.config[
    "SQLALCHEMY_DATABASE_URI"] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8"

db = SQLAlchemy(app)

migrate = Migrate(app, db)

# 测试数据库连接
with app.app_context():
    with db.engine.connect() as conn:
        rs = conn.execute(text("select 1"))
        print(rs.fetchone())


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    address = db.Column(db.String(255), nullable=False)

    age = db.Column(db.Integer)
    email = db.Column(db.String(100))


class Article(db.Model):
    __tablename__ = "article"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    content = db.Column(db.Text)

    # 添加作者的外键
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    # 给user模型自动添加articles属性用来获取文章列表
    author = db.relationship("User", backref="articles")


# 不建议用此方法创建,因为新增cloumn或者删除cloumn不会生效,这就需要使用flask-migrate迁移
# with app.app_context():
#     db.create_all()

"""
迁移分为三步
1. flask db init 只需要执行一次,会生成文件
2. flask db migrate 识别orm模型的改变,生成迁移文件
3. flask db upgrade  执行迁移脚本,同步到数据库中
"""


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


if __name__ == '__main__':
    app.run()
